#include "historydatawidget.h"
#include "ui_historydatawidget.h"

#include <QGridLayout>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

HistoryDataWidget::HistoryDataWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HistoryDataWidget)
{
    ui->setupUi(this);
    initUI();
    ui->dateEdit->setDate(QDate::currentDate());

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(InquiryData()));

    model = new QSqlTableModel(this);
    initModel("realTimeData");
    SetnodeNames();

}

HistoryDataWidget::~HistoryDataWidget()
{
    delete ui;
}
void HistoryDataWidget::initUI()
{
    mainlayout = new QGridLayout;
    mainlayout->addWidget(ui->label,0,0,1,1);
    mainlayout->addWidget(ui->dateEdit,0,1,1,2);
    mainlayout->addWidget(ui->label_2,0,4,1,1);
    mainlayout->addWidget(ui->comboBox,0,5,1,1);
    mainlayout->addWidget(ui->pushButton,0,8,1,1);
    mainlayout->addWidget(ui->tableView,1,0,1,10);
    setLayout(mainlayout);





}
void HistoryDataWidget::initModel(const QString &tableName)
{
    model->setTable(tableName);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);


}
void HistoryDataWidget::InquiryData()//查询数据
{
    model->setFilter(tr("name = %1 and _date = '%2'").arg(ui->comboBox->currentText().toInt())
                     .arg(ui->dateEdit->date().toString("yyyy-MM-dd")));
    model->select();
    model->setHeaderData(0, Qt::Horizontal, trUtf8("设备名"));
    model->setHeaderData(1, Qt::Horizontal, trUtf8("日期"));
    model->setHeaderData(2, Qt::Horizontal, trUtf8("时间"));
    model->setHeaderData(3, Qt::Horizontal, trUtf8("类型"));
    model->setHeaderData(4, Qt::Horizontal, trUtf8("值"));

    ui->tableView->setModel(model);
    for (int i = 0;i < 5;++i) {
        ui->tableView->horizontalHeader()->setResizeMode(i,QHeaderView::Stretch);

    }




    //此处根据日期和节点从相应的表中进行查询和相关的显示
}
void HistoryDataWidget::SetnodeNames()
{
    QSqlQuery query;
    QString sql = trUtf8("select DISTINCT name from realTimeData");
    if (query.exec(sql)) {
        while (query.next()) {
            ui->comboBox->addItem(query.value(0).toString());
        }
    }

}
